<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Mapper\ChTalkKeywordMapper;
use App\CustHub\Model\ChTalkKeyword;
use App\CustHub\Model\ChWord;
use Mine\Abstracts\AbstractService;

class ChTalkKeywordService extends AbstractService
{
    public $mapper;

    public function __construct(ChTalkKeywordMapper $mapper)
    {
        $this->mapper = $mapper;
    }


    public function searchKeywords(array $params): array
    {
        $userKeyword = $params['keyword'] ?? '';
        // 处理空关键词
        if (empty(trim($userKeyword))) {
            return [];
        }
        $uid = $params['uid'];
        $mainUid = $params['main_uid'];
        // 构建查询
        return ChWord::query()
            ->select(['id','title','content','content','msg_types'])
            ->where(function ($query) use ($uid,$mainUid){
                $query->where('cs_id', $uid)->where('is_personal',1)->orWhere(function ($query) use ($mainUid){
                    $query->where('main_uid', $mainUid)->where('is_personal',0);
                });
            })
            ->where(function ($query) use ($userKeyword) {
                // 精确匹配条件
                $query->where('match_type', 0)
                    ->where('keyword', $userKeyword);
            })
            ->orWhere(function ($query) use ($userKeyword) {
                // 模糊匹配条件
                $query->where('match_type', 1)
                    ->whereRaw('LOCATE(keyword, ?) > 0', [$userKeyword]);
            })
            ->orderByRaw('match_type ASC') // 精确匹配结果在前
            ->get()
            ->toArray();
    }
}